package org.swift.commons.client;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.log4j.Logger;

public class CookieUtil {
	private final static Logger log = Logger.getLogger(CookieUtil.class);
	private final static String COOKIE_DELIMETER = "; ";
	
	/**
	 * Generates a delimited string of cookie name/value pairs from the cookies on a request
	 * @param cookies array of Cookies from the incoming request
	 * @return "; " delimited string of cookie name/value pairs
	 */
	public static String generateCookieString(Cookie[] cookies){
		StringBuffer sb = new StringBuffer();
		if(cookies!=null && cookies.length>0){
			for(int i=0; i<cookies.length; i++){
				Cookie cookie = cookies[i];
				if(cookie != null) {
					sb.append(cookie.getName()).append("=").append(cookie.getValue());
					if(i!=cookies.length-1){
						sb.append(COOKIE_DELIMETER);
					}
				}
			}
			log.debug("Cookie String: "+sb.toString());
		}else{
			log.debug("No cookies found on request");
		}
		return sb.toString();		
	}
	
	/**
	 * Looks up the current Axis MessageContext and pulls cookies from the incoming request.
	 * @return "; " delimited string of cookie name/value pairs
	 */
	public static String generateCookieString(){
		return generateCookieString(getCookiesFromRequest());	
	}
	
	/**
	 * Turns an array of cookies into a List
	 * @param cookies cookies from request
	 * @return List of cookies
	 */
	public static List<Cookie> getCookieList(Cookie[] cookies){
		List<Cookie> cookieList = new ArrayList<Cookie>();
		if(cookies!=null && cookies.length>0){
			cookieList = Arrays.asList(cookies);
		}else{
			log.debug("No cookies found on request");
		}
		return cookieList;
	}
	
	/**
	 * Grabs the cookies from the request and returns them as a List
	 * @return
	 */
	public static List<Cookie> getCookieList(){
		return getCookieList(getCookiesFromRequest());
	}
	
	
	/**
	 * Grabs the cookies from the incoming request
	 * @return Cookie[] from request
	 */
	public static Cookie[] getCookiesFromRequest(){
		MessageContext ctx = (MessageContext)ContextUtil.getCurrentContext();
		if(ctx!=null){
			HttpServletRequest request = (HttpServletRequest) ctx.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
			try{
				Cookie[] cookies = request.getCookies();
				return cookies;
			}catch(Exception e){
				log.warn("Error retrieving cookies from request:"+e);
				return null;
			}
		}else{
			log.warn("No MessageContext found! Skipping request processing...");
		}
		return null;
	}
}
